"use client"

import {useEffect, useState} from "react"
import {Button} from "@/components/ui/button"
import {Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle} from "@/components/ui/card"
import {Input} from "@/components/ui/input"
import {Label} from "@/components/ui/label"
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
import {Switch} from "@/components/ui/switch"
import {Textarea} from "@/components/ui/textarea"
import {useAppStore} from "@/lib/store"
import {useToast} from "@/hooks/use-toast"
import {FileDown, FolderTree, Loader2, Upload} from "lucide-react"
import {ProjectEditor} from "@/components/project-editor"
import type {FileTreeItem} from "@/components/file-tree"
import FileSaver from "file-saver"

export function ProjectPanel() {
    const {toast} = useToast()
    const {projectConfig, setProjectConfig, todoList, setIsLoading} = useAppStore()
    const [isDeploying, setIsDeploying] = useState(false)
    const [isDownloading, setIsDownloading] = useState(false)
    const [projectFiles, setProjectFiles] = useState<FileTreeItem[]>([])
    const [activeTab, setActiveTab] = useState<"config" | "editor" | "deploy">("config")

    // 生成项目文件结构
    useEffect(() => {
        const generateProjectStructure = async () => {
            // 只有当有任务项且没有文件结构时才生成
            if (todoList.length > 0 && projectFiles.length === 0) {
                try {
                    setIsLoading(true)

                    // 基本文件结构
                    const baseFiles: FileTreeItem[] = [
                        {
                            name: "src",
                            path: "src",
                            type: "directory",
                            children: [
                                {
                                    name: "components",
                                    path: "src/components",
                                    type: "directory",
                                    children: [],
                                },
                                {
                                    name: "views",
                                    path: "src/views",
                                    type: "directory",
                                    children: [],
                                },
                                {
                                    name: "assets",
                                    path: "src/assets",
                                    type: "directory",
                                    children: [],
                                },
                                {
                                    name: "App.vue",
                                    path: "src/App.vue",
                                    type: "file",
                                },
                                {
                                    name: "main.ts",
                                    path: "src/main.ts",
                                    type: "file",
                                },
                            ],
                        },
                        {
                            name: "public",
                            path: "public",
                            type: "directory",
                            children: [],
                        },
                        {
                            name: "package.json",
                            path: "package.json",
                            type: "file",
                        },
                        {
                            name: "vite.config.ts",
                            path: "vite.config.ts",
                            type: "file",
                        },
                        {
                            name: "tsconfig.json",
                            path: "tsconfig.json",
                            type: "file",
                        },
                        {
                            name: "index.html",
                            path: "index.html",
                            type: "file",
                        },
                    ]

                    // 为每个已完成的任务添加组件文件
                    const componentsDir = baseFiles[0].children?.find((item) => item.name === "components")
                    if (componentsDir && componentsDir.children) {
                        todoList.forEach((todo) => {
                            if (todo.generatedCode) {
                                const componentName = todo.title
                                    .replace(/[^a-zA-Z0-9]/g, " ")
                                    .split(" ")
                                    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                                    .join("")

                                componentsDir.children?.push({
                                    name: `${componentName}.vue`,
                                    path: `src/components/${componentName}.vue`,
                                    type: "file",
                                })
                            }
                        })
                    }

                    setProjectFiles(baseFiles)
                } catch (error) {
                    console.error("Error generating project structure:", error)
                    toast({
                        title: "生成项目结构失败",
                        description: "无法生成项目文件结构，请重试",
                        variant: "destructive",
                    })
                } finally {
                    setIsLoading(false)
                }
            }
        }

        generateProjectStructure()
    }, [todoList, projectFiles.length, setIsLoading, toast])

    const handleSaveConfig = () => {
        toast({
            title: "配置已保存",
            description: "项目配置已更新",
        })
    }

    const handleDeployDocker = async () => {
        if (!projectConfig.dockerRepo || !projectConfig.dockerUsername) {
            toast({
                title: "配置不完整",
                description: "请填写Docker仓库地址和用户名",
                variant: "destructive",
            })
            return
        }

        setIsDeploying(true)

        try {
            // 模拟部署过程
            await new Promise((resolve) => setTimeout(resolve, 3000))

            toast({
                title: "部署成功",
                description: `项目已成功部署到 ${projectConfig.dockerRepo}`,
            })
        } catch (error) {
            toast({
                title: "部署失败",
                description: "Docker部署过程中出现错误",
                variant: "destructive",
            })
        } finally {
            setIsDeploying(false)
        }
    }

    const handleDownloadProject = () => {
        if (todoList.filter((t) => t.generatedCode).length === 0) {
            toast({
                title: "没有可下载的代码",
                description: "请先在AI助手中生成代码",
                variant: "destructive",
            })
            return
        }

        setIsDownloading(true)

        // 模拟下载过程
        setTimeout(() => {
            setIsDownloading(false)
            toast({
                title: "下载成功",
                description: "项目代码包已下载",
            })
            const content = "假装这里是项目代码的zip文件内容"
            FileSaver.saveAs(content, "vue-project.zip")
        }, 2000)
    }

    const handleSaveFile = (path: string, content: string) => {
        // 在实际应用中，这里会保存文件内容
        console.log(`Saving file ${path} with content:`, content)
    }

    return (
        <div className="space-y-6">
            <Tabs
                value={activeTab}
                onValueChange={(value) => setActiveTab(value as "config" | "editor" | "deploy")}
                className="w-full"
            >
                <TabsList className="grid w-full grid-cols-3">
                    <TabsTrigger value="config">项目配置</TabsTrigger>
                    <TabsTrigger value="editor">项目编辑器</TabsTrigger>
                    <TabsTrigger value="deploy">部署选项</TabsTrigger>
                </TabsList>

                <TabsContent value="config" className="space-y-4 mt-4">
                    <Card>
                        <CardHeader>
                            <CardTitle>基本配置</CardTitle>
                            <CardDescription>设置项目的基本信息</CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="project-name">项目名称</Label>
                                    <Input
                                        id="project-name"
                                        value={projectConfig.name}
                                        onChange={(e) => setProjectConfig({name: e.target.value})}
                                        placeholder="vue-project"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="vue-version">Vue版本</Label>
                                    <Input
                                        id="vue-version"
                                        value={projectConfig.vueVersion}
                                        onChange={(e) => setProjectConfig({vueVersion: e.target.value})}
                                        placeholder="3.3"
                                    />
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="project-description">项目描述</Label>
                                <Textarea
                                    id="project-description"
                                    value={projectConfig.description}
                                    onChange={(e) => setProjectConfig({description: e.target.value})}
                                    placeholder="项目描述..."
                                    rows={3}
                                />
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="flex items-center space-x-2">
                                    <Switch
                                        id="include-router"
                                        checked={projectConfig.includeRouter}
                                        onCheckedChange={(checked) => setProjectConfig({includeRouter: checked})}
                                    />
                                    <Label htmlFor="include-router">包含Vue Router</Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Switch
                                        id="include-pinia"
                                        checked={projectConfig.includePinia}
                                        onCheckedChange={(checked) => setProjectConfig({includePinia: checked})}
                                    />
                                    <Label htmlFor="include-pinia">包含Pinia</Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Switch
                                        id="include-vitest"
                                        checked={projectConfig.includeVitest}
                                        onCheckedChange={(checked) => setProjectConfig({includeVitest: checked})}
                                    />
                                    <Label htmlFor="include-vitest">包含Vitest测试</Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Switch
                                        id="include-eslint"
                                        checked={projectConfig.includeEslint}
                                        onCheckedChange={(checked) => setProjectConfig({includeEslint: checked})}
                                    />
                                    <Label htmlFor="include-eslint">包含ESLint</Label>
                                </div>
                            </div>
                        </CardContent>
                        <CardFooter>
                            <Button onClick={handleSaveConfig}>保存配置</Button>
                        </CardFooter>
                    </Card>
                </TabsContent>

                <TabsContent value="editor" className="space-y-4 mt-4">
                    <Card>
                        <CardHeader>
                            <CardTitle>项目编辑器</CardTitle>
                            <CardDescription>查看和编辑项目文件</CardDescription>
                        </CardHeader>
                        <CardContent>
                            {projectFiles.length > 0 ? (
                                <ProjectEditor files={projectFiles} onSave={handleSaveFile}/>
                            ) : (
                                <div className="flex flex-col items-center justify-center py-12 text-center">
                                    <FolderTree className="h-16 w-16 text-muted-foreground mb-4"/>
                                    <h3 className="text-lg font-medium mb-2">没有项目文件</h3>
                                    <p className="text-muted-foreground mb-4">请先在AI助手中生成组件代码，或者手动创建项目文件</p>
                                    <Button onClick={() => setActiveTab("config")}>配置项目</Button>
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>

                <TabsContent value="deploy" className="space-y-4 mt-4">
                    <Card>
                        <CardHeader>
                            <CardTitle>Docker部署配置</CardTitle>
                            <CardDescription>配置Docker部署选项</CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="docker-repo">Docker仓库地址</Label>
                                <Input
                                    id="docker-repo"
                                    value={projectConfig.dockerRepo || ""}
                                    onChange={(e) => setProjectConfig({dockerRepo: e.target.value})}
                                    placeholder="例如：docker.io/username/repo"
                                />
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="docker-username">Docker用户名</Label>
                                    <Input
                                        id="docker-username"
                                        value={projectConfig.dockerUsername || ""}
                                        onChange={(e) => setProjectConfig({dockerUsername: e.target.value})}
                                        placeholder="Docker用户名"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="docker-password">Docker密码</Label>
                                    <Input
                                        id="docker-password"
                                        type="password"
                                        value={projectConfig.dockerPassword || ""}
                                        onChange={(e) => setProjectConfig({dockerPassword: e.target.value})}
                                        placeholder="Docker密码"
                                    />
                                    <p className="text-xs text-muted-foreground">密码不会被永久存储，仅在部署时使用</p>
                                </div>
                            </div>
                        </CardContent>
                        <CardFooter className="flex justify-between">
                            <Button variant="outline" onClick={handleDownloadProject} disabled={isDownloading}>
                                {isDownloading ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin"/>
                                        下载中...
                                    </>
                                ) : (
                                    <>
                                        <FileDown className="mr-2 h-4 w-4"/>
                                        下载项目
                                    </>
                                )}
                            </Button>
                            <Button
                                onClick={handleDeployDocker}
                                disabled={isDeploying || !projectConfig.dockerRepo || !projectConfig.dockerUsername}
                            >
                                {isDeploying ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin"/>
                                        部署中...
                                    </>
                                ) : (
                                    <>
                                        <Upload className="mr-2 h-4 w-4"/>
                                        部署到Docker
                                    </>
                                )}
                            </Button>
                        </CardFooter>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>部署历史</CardTitle>
                            <CardDescription>查看项目的部署历史记录</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="text-center py-8 text-muted-foreground">
                                <p>暂无部署历史记录</p>
                            </div>
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </div>
    )
}
